package com.bds.btcdc.web.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.api.TradeService;
import com.bds.btcdc.api.model.AccountInfo;
import com.bds.btcdc.api.model.AccountInfoDto;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.service.AccountInfoService;
import com.bds.btcdc.web.service.AssetExchangeService;
import com.bds.btcdc.web.service.PairConverterService;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.List;


/**
 * Created by DongChenchen on 2018/5/9 0009
 * 账户中心
 */
@Controller
public class AccountAction extends BaseAction{
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private AccountInfoService accountInfoService;
    @Autowired
    private TradeService tradeService;
    @Autowired
    private AssetExchangeService assetExchangeService;
    @Autowired
    private PairConverterService pairConverterService;

    private DecimalFormat df = new DecimalFormat(Const.END_WITH_COUNT);
    /**
     * 跳转到资产信息界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/account/asset_info")
    public String assetInfo(HttpServletRequest request, Model model) {
        logger.info("--------------------------跳转到资产信息界面------------------------");
        try {
            Long user_id = CookieUtils.getUserIdfromCookie(request);
            if(user_id==null){
                model.addAttribute("msg", "未获取到数据,请先登录！");
            }else {
                //先从数据库中取,没有在api获取
                long start = System.currentTimeMillis();
                List<AccountInfo> accountInfos = assetExchangeService.getAccountInfos(user_id);
                if(!CollectionUtils.isEmpty(accountInfos)) {
                    AccountInfoDto accountInfoDto = accountInfoService.caculate(accountInfos, user_id);
                    model.addAttribute("accountInfoDto", accountInfoDto);
                    long end = System.currentTimeMillis();
                    logger.info("从数据库中获取资产情况，耗时："+(end-start));
                }else{
                    Result nodeResult1 = tradeService.getAccount(user_id);
                    if (nodeResult1.getCode() == Const.SUC) {
                        JSONArray arrays = JSONObject.parseArray(nodeResult1.getData().toString());
                        List<AccountInfo> infos = arrays.toJavaList(AccountInfo.class);
                        AccountInfoDto accountInfoDto = accountInfoService.caculate(infos, user_id);
                        model.addAttribute("accountInfoDto", accountInfoDto);
                        //更新数据库
                        assetExchangeService.updateAccountInfos(infos);
                    } else {
                        model.addAttribute("msg", "未获取到数据,异常为：" + nodeResult1.getMsg());
                    }
                    long end = System.currentTimeMillis();
                    logger.info("API获取资产情况，耗时："+(end-start));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","未获取到数据,发生异常："+e.getMessage());
        }
        return "ftl/account/asset_info";
    }

    /**
     * 获取用户资产信息
     * param request
     * @return
     */
    @RequestMapping("/account/get_accet_info")
    @ResponseBody
    public String getAsset(HttpServletRequest request) {
        logger.info("--------------------------跳转到资产信息界面------------------------");
        Result res=new Result();
        try {
            Long user_id = CookieUtils.getUserIdfromCookie(request);
            if(user_id==null){
                res.setResult(Const.FAIL, "未获取到数据,请先登录！");
            }else {
                Result nodeResult1 = tradeService.getAccount(user_id);
                if (nodeResult1.getCode() == Const.SUC) {
                    JSONArray arrays=JSONObject.parseArray(nodeResult1.getData().toString());
                    List<AccountInfo> infos =arrays.toJavaList(AccountInfo.class);
                    //更新数据库
                    assetExchangeService.updateAccountInfos(infos);
                    res.setResult(Const.SUC,"更新成功！");
                } else {
                    res.setResult(Const.FAIL,  "未获取到数据,异常为：" + nodeResult1.getMsg());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            res.setResult(Const.FAIL, "未获取到数据,发生异常："+e.getMessage());
        }
        return "success_jsonpCallback"+"("+this.parseJson(res)+")";
    }
}
